<template>
    <el-dialog
        v-model="isDialog" class="addContract" :close-on-click-modal="false" :close-on-press-escape="false"
        :before-close="closeDialog" append-to-body
    >
        <template #header>
            <div class="dialog-header flexR-Cen">
                <el-image v-if="isPc" class="image" :src="img3" fit="cover" />
                <span>{{ contractData.lxlxStr + '-' + contractData.lxsyzlStr }}</span>
            </div>
        </template>

        <el-form
            ref="formRef" class="formBox" :disabled="isDisabled" label-position="left" :model="formData"
            :rules="rules"
        >
            <el-row class="rowBox" :gutter="20">
                <el-col :span="24">
                    <p class="title flexR-FS-C"><span /><span>基本信息</span></p>
                </el-col>
                <el-col :xs="24" :sm="24" :md="24" :lg="6" :xl="6">
                    <el-form-item prop="gcmc">
                        <template #label>
                            <span :class="isPc ? 'width60' : 'width70'">工程名称</span>
                        </template>
                        <el-input
                            v-model="formData.gcmc" class="formInit" disabled placeholder="请输入"
                            placeholder-class="plaClass" :style="{ width: '100%' }"
                        />
                    </el-form-item>
                </el-col>
                <el-col :xs="24" :sm="24" :md="24" :lg="6" :xl="6">
                    <el-form-item prop="lxmc">
                        <template #label>
                            <span :class="isPc ? 'width60' : 'width70'">{{ contractData.lxsyzl == '2' &&
                                contractData.lxsyzlStr == '补充' ? '原立项' :
                                    '合同名称' }}</span>
                        </template>
                        <el-input
                            v-model="formData.lxmc" class="formInit" :disabled="contractData.lxsyzlStr == '补充'"
                            placeholder="请输入" placeholder-class="plaClass" :style="{ width: '100%' }"
                        />
                    </el-form-item>
                </el-col>
                <el-col :xs="24" :sm="24" :md="24" :lg="6" :xl="6">
                    <el-form-item prop="lxlx">
                        <template #label>
                            <span :class="isPc ? 'width60' : 'width70'">合同类型</span>
                        </template>
                        <el-select
                            v-model="formData.lxlx" disabled placeholder="请选择" clearable
                            :style="{ width: '100%' }"
                        >
                            <el-option
                                v-for="(value, key, index) in contractOptions" :key="index" :label="value"
                                :value="key"
                            />
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :xs="24" :sm="24" :md="24" :lg="6" :xl="6">
                    <el-form-item prop="zzyq">
                        <template #label>
                            <span :class="isPc ? 'width60' : 'width70'">资质要求</span>
                        </template>
                        <el-select
                            v-model="formData.zzyq" clearable filterable remote placeholder="请输入相关字段"
                            remote-show-suffix :remote-method="remoteMethod" :loading="zzyqLoading"
                            :style="{ width: '100%' }"
                        >
                            <el-option
                                v-for="item in zzyqOptions" :key="item.id" :label="item.zzlb"
                                :value="item.zzlb"
                            />
                        </el-select>
                    </el-form-item>
                </el-col>
            </el-row>

            <el-row class="rowBox" :gutter="20">
                <el-col :span="24">
                    <p class="title flexR-FS-C"><span /><span>主要工程量</span></p>
                </el-col>
                <el-col :xs="24" :sm="24" :md="24" :lg="12" :xl="12">
                    <el-form-item prop="zygcl" style="border: 0;">
                        <template #label>
                            <span :class="isPc ? 'width110' : 'width90'">主要工程量</span>
                        </template>
                        <el-input
                            v-model="formData.zygcl" class="formInit" placeholder="请输入"
                            :style="{ width: '100%' }"
                        />
                    </el-form-item>
                </el-col>
                <el-col :xs="24" :sm="24" :md="24" :lg="12" :xl="12">
                    <el-form-item prop="zghtjwy">
                        <template #label>
                            <span :class="isPc ? 'width150' : 'width90'">初始立项/暂估合同价</span>
                        </template>
                        <el-input
                            v-model="formData.zghtjwy" class="formInit" placeholder="请输入"
                            :style="{ width: '100%' }"
                        >
                            <template #append>万元</template>
                        </el-input>
                    </el-form-item>
                </el-col>
            </el-row>

            <el-row class="rowBox" :gutter="20">
                <el-col :span="24">
                    <p class="title flexR-FS-C"><span /><span>工作范围</span></p>
                </el-col>
                <el-col :span="24">
                    <el-form-item prop="gzfwjnr" style="border: 0;">
                        <template #label>
                            <span :class="isPc ? 'width120' : 'width100'">工作范围及内容</span>
                        </template>
                        <el-input
                            v-model="formData.gzfwjnr" type="textarea" placeholder="请输入" :maxlength="200"
                            show-word-limit :autosize="{ minRows: 2, maxRows: 2 }" :style="{ width: '100%' }"
                        />
                    </el-form-item>
                </el-col>
                <el-col :xs="24" :sm="24" :md="24" :lg="12" :xl="12">
                    <el-form-item prop="cgxs">
                        <template #label>
                            <span :class="isPc ? 'width120' : 'width100'">采购形式</span>
                        </template>
                        <el-select
                            v-model="formData.cgxs" class="formInit" placeholder="请选择" clearable
                            :style="{ width: '100%' }"
                        >
                            <el-option
                                v-for="(value, key, index) in cgxsOptions" :key="index" :label="value"
                                :value="key"
                            />
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :xs="24" :sm="24" :md="24" :lg="12" :xl="12">
                    <el-form-item prop="jhqdrq">
                        <template #label>
                            <span :class="isPc ? 'width110' : 'width70'">计划签订日期</span>
                        </template>
                        <el-date-picker
                            v-model="formData.jhqdrq" class="formInit" style="width: 100%;" type="month"
                            placeholder="请选择"
                        />
                    </el-form-item>
                </el-col>
            </el-row>

            <el-row class="rowBox" :gutter="20">
                <template v-if="contractData.lxsyzl == '4'">
                    <el-col :span="12">
                        <el-form ref="formRef2" :model="formData" :rules="rules2">
                            <el-form-item prop="lxsysm" style="border: 0;">
                                <template #label>
                                    <span :class="isPc ? 'width110' : 'width70'">销项事由</span>
                                </template>
                                <el-input
                                    v-model="formData.lxsysm" class="fz14" :disabled="formData.lxsyzl == 4" type="textarea" placeholder="请输入"
                                    :maxlength="200" show-word-limit :autosize="{ minRows: 2, maxRows: 2 }"
                                    :style="{ width: '100%' }"
                                />
                            </el-form-item>
                        </el-form>
                    </el-col>
                </template>
                <template v-else>
                    <el-col :span="24">
                        <p class="title flexR-FS-C"><span /><span>立项事由</span></p>
                    </el-col>
                    <el-col :span="12">
                        <el-row>
                            <el-col :span="24">
                                <el-form-item prop="lxsyzl">
                                    <template #label>
                                        <span :class="isPc ? 'width110' : 'width70'">种类</span>
                                    </template>
                                    <el-radio-group v-model="formData.lxsyzl" class="formInit">
                                        <el-radio
                                            v-for="(item, key, index) in lxsyzlOptions" :key="index" :label="key"
                                            size="large"
                                        >
                                            {{ item }}
                                        </el-radio>
                                    </el-radio-group>
                                </el-form-item>
                            </el-col>
                            <el-col :span="24">
                                <el-form-item prop="lxsysm" style="border: 0;">
                                    <template #label>
                                        <span :class="isPc ? 'width110' : 'width70'">说明</span>
                                    </template>
                                    <el-input
                                        v-model="formData.lxsysm" class="fz14" type="textarea" placeholder="请输入"
                                        :maxlength="200" show-word-limit :autosize="{ minRows: 2, maxRows: 2 }"
                                        :style="{ width: '100%' }"
                                    />
                                </el-form-item>
                            </el-col>
                            <el-col :span="24">
                                <el-form-item label="相关依据" prop="xgyj" style="border: 0;">
                                    <template #label>
                                        <span :class="isPc ? 'width110' : 'width70'">相关依据</span>
                                    </template>
                                    <el-input
                                        v-model="formData.xgyj" type="textarea" placeholder="请输入" :maxlength="200"
                                        show-word-limit :autosize="{ minRows: 2, maxRows: 2 }"
                                        :style="{ width: '100%' }"
                                    />
                                </el-form-item>
                            </el-col>
                        </el-row>
                    </el-col>
                </template>
                <el-col :span="12">
                    <el-form-item prop="name">
                        <template #label>
                            <span :class="isPc ? 'width110' : 'width70'">附件上传</span>
                        </template>
                        <div class="w100 flexR-SB-FS">
                            <el-upload
                                v-if="!isDisabled" class="upload-demo fz13" drag action=""
                                :show-file-list="false" :auto-upload="false" :before-upload="handleBeforeUpload"
                                :on-change="handleFileChange"
                            >
                                <el-icon class="el-icon--upload"><upload-filled /></el-icon>
                                <div class="el-upload__text">
                                    拖动文件或 <em>点击上传</em>
                                </div>

                                <template #tip>
                                    <div class="el-upload__tip">
                                        单个文件不能超过500M
                                    </div>
                                </template>
                            </el-upload>

                            <div class="filesBox flexC-FS-FS">
                                <div v-for="(item, index) in fileProgressList" :key="index" class="w100">
                                    <el-divider content-position="left">
                                        {{ item.fileName }}
                                        <template v-if="!item.percent || item.percent !== 0">
                                            <el-form :model="formData" inline>
                                                <el-tooltip
                                                    v-if="!(item.percent >= 0)" :disabled="false" effect="dark"
                                                    content="下载" placement="top-start"
                                                >
                                                    <el-button
                                                        class="circel-btn" style="color: #666;" :icon="Download"
                                                        circle @click="handleDownFile(item)"
                                                    />
                                                </el-tooltip>
                                                <el-tooltip content="删除" placement="top-start">
                                                    <el-button
                                                        class="circel-btn" :disabled="isDisabled"
                                                        style="color: #ff3141;" :icon="Delete" circle
                                                        @click="handleDeleteFile(index)"
                                                    />
                                                </el-tooltip>
                                            </el-form>
                                        </template>
                                    </el-divider>
                                    <el-progress
                                        v-if="item.percent >= 0" :percentage="item.percent"
                                        :status="item.percent == 100 ? 'success' : ''"
                                        :indeterminate="item.percent == 100 ? false : true"
                                    />
                                </div>
                            </div>
                        </div>
                    </el-form-item>
                </el-col>
            </el-row>
        </el-form>

        <template #footer>
            <el-button @click="closeDialog()">关闭</el-button>
            <el-button
                v-if="contractData.lxsyzlStr !== '查看'" v-loading="isLoading"
                v-debounce="handleConfirm" :type="contractData.lxsyzl == '4' ? 'danger' : 'primary'"
            >
                {{
                    contractData.lxsyzlStr }}
            </el-button>
        </template>
    </el-dialog>
</template>

<script setup>
import { getSupplierlistApi, saveContractDetailApi } from '@/api/contract'
import { downloadFileApi } from '@/api/system'

import { contractOptions, cgxsOptions, lxsyzlOptions } from '@/components/common'
import fileUploadData from '@/hooks/fileUpload'
import commonData from '@/hooks/commonData'
import { formatDate } from '@/utils/time'
import { getFloat } from '@/utils'
import { saveAs } from 'file-saver'

const emit = defineEmits(['success'])
defineProps({
    title: {
        type: String,
        default: ''
    }
})
const { getContractData, UploadFilled, isPc, paginationQuery, img3, Download, Delete } = commonData()

const formRef = ref()
const formRef2 = ref()
const contractData = ref({})
const isDisabled = computed(() => contractData.value.lxsyzl == 4 || contractData.value.lxsyzlStr == '查看')

// 文件上传数据
const { handleBeforeUpload, handleFileChange, fileProgressList } = fileUploadData()

const detailData = inject('detailData')

// 资质要求选项
const zzyqAllOptions = ref()
const zzyqOptions = ref()
const formData = reactive({
    'gcmc': '',
    'uuid': '',
    'lxUuid': '',
    'lxmc': '', // 立项名称
    'zzyq': '', // 资质要求
    'lxlx': '', // 立项类型
    'zygcl': '', // 主要工程量
    'zghtjwy': 0, // 暂估合同价（）
    // 'dtjewy': 303000.1253, //动态金额（）
    'gzfwjnr': '', // 工作范围及内容
    'cgxs': '3', // 采购形式
    'jhqdrq': new Date(), // 计划签订日期
    'lxsyzl': '', // 立项事由-种类
    'lxsysm': '', // 立项事由说明
    'xgyj': '', // 相关依据
    'attachments': []
})
const rowData = ref()

const state = reactive({
    isDialog: false,
    isLoading: false,
    zzyqLoading: false,
    nameList: [],
    rules: {
        gcmc: [
            {
                required: true,
                message: '请输入合同名称',
                trigger: 'blur'
            }
        ],
        lxmc: [
            {
                required: true,
                message: '合同名称必填',
                trigger: 'blur'
            }
        ],
        lxlx: [
            {
                required: true,
                message: '合同类型必填',
                trigger: 'blur'
            }
        ],
        zzyq: [
            {
                required: true,
                message: '资质要求必填',
                trigger: 'blur'
            }
        ],
        zygcl: [
            {
                required: true,
                message: '主要工程量必填',
                trigger: 'blur'
            }
        ],
        zghtjwy: [
            {
                required: true,
                message: '初始立项/暂估合同价必填',
                trigger: 'blur'
            }
        ],
        /* dtjewy: [
            {
                required: true,
                message: '动态立项金额必填',
                trigger: 'blur'
            }
        ], */
        gzfwjnr: [
            {
                required: true,
                message: '工作范围及内容必填',
                trigger: 'blur'
            }
        ],
        jhqdrq: [
            {
                required: true,
                message: '签订日期必填',
                trigger: 'blur'
            }
        ],
        cgxs: [
            {
                required: true,
                message: '采购形式必填',
                trigger: 'blur'
            }
        ],
        lxsyzl: [
            {
                required: true,
                message: '立项事由-种类必填',
                trigger: 'blur'
            }
        ],
        lxsysm: [
            {
                required: true,
                message: '立项/销项事由说明必填',
                trigger: 'blur'
            }
        ],
        xgyj: [
            {
                required: true,
                message: '相关依据必填',
                trigger: 'blur'
            }
        ]
    },

    rules2: {
        lxsysm: [
            {
                required: true,
                message: '销项事由必填',
                trigger: 'blur'
            }
        ]
    }
})

const {
    isDialog,
    isLoading,
    zzyqLoading,
    // nameList,
    rules,
    rules2
} = toRefs(state)

// 展示弹框
function show(row) {
    rowData.value = row
    contractData.value = getContractData()
    getZzyqOptions()
    isDialog.value = true

    nextTick(() => {
        resetQuery()
        formData.gcmc = contractData.value.projectName
        formData.uuid = contractData.value.contractInitiationUuId
        formData.lxsyzl = row.lxsyzl || contractData.value.lxsyzl
        formData.lxlx = contractData.value.lxlx
        formData.attachments = []
        // jhqdrq
        if (row.lxUuid) {
            const excludedProperties = ['gcmc', 'uuid', 'lxsyzl', 'lxlx']
            for (const key in formData) {
                if (!excludedProperties.includes(key)) {
                    if (key == 'cgxs') {
                        formData[key] = String(row[key])
                    } else if (key == 'zghtjwy') {
                        formData[key] = getFloat(row[key], 4)
                    } else {
                        formData[key] = row[key]
                    }
                }
            }
        }

        if (contractData.value.lxsyzl == 4 && !(contractData.value.lxsyzlStr == '查看')) {
            formData.lxsysm = ''
        }
        fileProgressList.value = formData.attachments || []
    })
}

// 资质要求选项
async function getZzyqOptions() {
    paginationQuery.pageSize = 900
    const { data } = (await getSupplierlistApi(paginationQuery))
    if (data && data.length) {
        zzyqAllOptions.value = data
        zzyqOptions.value = zzyqAllOptions.value
    }
}

function remoteMethod(query) {
    if (query) {
        zzyqLoading.value = true
        setTimeout(() => {
            zzyqOptions.value = zzyqAllOptions.value.filter(item => {
                return item.zzlb.toLowerCase().includes(query.toLowerCase())
            })
            zzyqLoading.value = false
        }, 200)
    } else {
        zzyqOptions.value = zzyqAllOptions.value
    }
}

// 确认提交
function handleConfirm() {
    if (fileProgressList.value.length && fileProgressList.value.some(el => el.percent && el.percent >= 0 && el.percent < 100)) {
        ElMessage.warning('文件正在上传中，请稍后提交')
        return
    }

    formRef.value.validate(async valid => {
        if (valid) {
            // let valid2 = false;
            if (contractData.value.lxsyzl == 4) {
                const valid2 = await formRef2.value.validate()
                if (!valid2) {
                    return
                }
            }
            formData.attachments = fileProgressList.value.map(item => {
                return {
                    fileName: item.fileName,
                    guid: item.guid,
                    filePath: item.filePath
                }
            })
            isLoading.value = true
            // 新增、补充、销项都是保存接口
            handleAddOrEdit()
        }
    })
}

// 合同新增、补充
function handleAddOrEdit() {
    const newFormData = JSON.parse(JSON.stringify(formData))
    newFormData.jhqdrq = formatDate(formData.jhqdrq).fmt6

    if (contractData.value.lxsyzl == 4) {
        newFormData.lxsyzl = 4
    }
    // 补充 传入父id
    if (rowData.value.lxStatus == 9) {
        newFormData.lxParentUuid = newFormData.lxUuid
        newFormData.lxUuid = ''
    }
    saveContractDetailApi(newFormData).then(data => {
        handleResponse(data)
    }).finally(() => {
        isLoading.value = false
    })
}

// 下载fileProgressList指定路由的文件
async function handleDownFile(item) {
    const data = {
        fileName: item.filePath
    }
    const res = await downloadFileApi(data)
    saveAs(
        new Blob(
            [res],
            { type: 'application/vnd.ms-excel;charset=utf-8' }
        ),
        item.fileName)
}

// 删除fileProgressList指定下标的文件
function handleDeleteFile(index) {
    fileProgressList.value.splice(index, 1)
}

// 处理响应数据
function handleResponse(data) {
    if (data.data) {
        if (data.data.lxUuid || (data.data.code == 0)) {
            ElMessage.success(`${contractData.value.lxsyzlStr}成功`)
            successCalback()
        }
    } else {
        ElMessage.error(data.errMsg)
    }
}

function successCalback() {
    emit('success')
    closeDialog()
}

/**
 * 重置
 */
function resetQuery() {
    for (const key in formData) {
        formData[key] = ''
    }
    formRef.value.resetFields()
}

// 关闭弹框
function closeDialog() {
    isDialog.value = false
}

// 暴露方法给外部使用
defineExpose({
    show,
    closeDialog
})
</script>

<style scoped lang='scss'>
[data-mode="pc"] {
    .addContract {
        padding: 32px;
        .dialog-header {
            padding-bottom: 20px;
            border-bottom: 1px solid #f5f5f5;
            .image {
                width: 35px;
                height: 35px;
                margin-right: 15px;
            }
        }
        .formBox {
            margin-top: 20px;
            .title {
                width: 128px;
                height: 27px;
                background: linear-gradient(270deg, #fff 0%, rgb(1 112 254 / 20%) 100%);
                margin-bottom: 18px;
                span:first-child {
                    width: 8px;
                    height: 20px;
                    background: #0170fe;
                    display: block;
                    margin: 0 6px 0 12px;
                }
                span:last-child {
                    font-size: 16px;
                    font-family: PingFangSC, "PingFang SC";
                    color: rgb(0 0 0);
                }
            }
            .rowBox {
                width: 100%;
                margin-top: 20px;
                border-bottom: 1px dashed #979797;
                &:first-child {
                    margin-top: 0;
                }
                &:last-child {
                    border: 0 none;
                }
            }
            .upload-demo {
                width: 30%;
            }
            .filesBox {
                width: 65%;
                margin-left: 20px;
                .circel-btn {
                    width: 25px;
                    height: 25px;
                    font-size: 12px;
                    margin-left: 10px;
                }
            }
        }
    }
}
[data-mode="mobile"] {
    .addContract {
        .rowBox {
            border-bottom: 0 none;
            padding-bottom: 0;
            margin-top: 15px;
        }
        .dialog-header {
            border-bottom: 0 none;
            padding-bottom: 0;
        }
    }
}
</style>

<style lang="scss">
.addContract {
    .el-form-item--default .el-form-item__label {
        font-size: 14px;
        color: rgb(0 0 0);
        height: auto;
    }
}
[data-mode="pc"] {
    .addContract {
        width: 80%;
        margin: 40px auto 20px;
        &.el-dialog {
            padding: 15px 25px;
        }
        .el-dialog__header {
            padding-bottom: 0;
        }
        .el-form-item__label {
            font-size: 13px;
        }
        .el-form-item__label,
        .el-radio.el-radio--large .el-radio__label {
            display: flex;
            flex-direction: row;
            justify-content: flex-start;
            align-items: center;
        }
        .formInit,
        .el-select__wrapper,
        .el-radio.el-radio--large .el-radio__label {
            height: 30px;
            font-size: 13px;
        }
        .el-upload-dragger .el-upload__text,
        .el-upload__tip {
            font-size: 12px;
        }
        .el-upload-dragger {
            padding: 10px;
        }
        .el-dialog__footer {
            padding-top: 0;
        }
        .el-divider--horizontal {
            margin: 30px 0;
            .el-divider__text {
                font-size: 13px;
            }
        }
    }
}
[data-mode="mobile"] {
    .addContract {
        width: 93%;
        border-radius: 8px;
        &.el-dialog {
            padding: 15px;
        }
        .el-form-item {
            border-bottom: 1px solid #e2e1e1;
            padding-bottom: 3px;
        }
        .el-input__wrapper,
        .el-select__wrapper {
            box-shadow: none;
        }
        .el-input__inner,
        .el-textarea__inner {
            &::placeholder {
                text-align: right;
                margin-right: 20px;
            }
        }
        .el-select__placeholder.is-transparent {
            text-align: right;
        }
    }
}
</style>
